const fs = require("fs");
const path = require("path");

const imgFormat = [".jpg", ".jpeg", ".png", ".bmp", ".svg", ".gif", ".webp"];
const serverPath = "http://127.0.0.1:8080";

try {
  // 文件夹路径
  /** 常用文件夹路径
   * wallPaper壁纸路径 "F:/Program Files/Steam/steamapps/workshop/content"
   *  */
  const rootPath = fs.readFileSync("./文件夹路径.txt")?.toString();
  const escapedRootPath = rootPath.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");

  // 替换本地文件路径为网络路径
  const replacedJsonString = (path) => {
    const str1 = path.replace(new RegExp(escapedRootPath, "g"), serverPath);
    const str2 = str1.replace(/\\/g, "/");
    return str2;
  };

  const directoryTree = buildDirectoryTree(rootPath?.toString());
  // console.log("目录", directoryTree);

  // 将数组转换为JSON字符串
  const jsonString = JSON.stringify(directoryTree);
  // 同步写入JSON文件
  fs.writeFileSync("../public/images.json", jsonString);
  console.log("Array has been saved to myArray.json");

  // 递归构建目录树
  function buildDirectoryTree(_rootPath, tree = {}) {
    // 获取指定路径下的所有文件和目录
    fs.readdirSync(_rootPath).forEach((item) => {
      // console.log("fs.readdirSync ~ rootPath:", rootPath);
      const fullPath = path.join(_rootPath, item);
      const stats = fs.statSync(fullPath);

      // 如果是目录，则递归调用
      if (stats.isDirectory()) {
        // 为当前目录创建一个子目录对象
        if (!tree[item]) {
          tree[item] = {};
        }
        // 递归遍历子目录
        buildDirectoryTree(fullPath, tree[item]);
      }
      if (stats.isFile()) {
        // 如果是文件，则判断是否为图片文件
        const extname = path.extname(item);
        if (imgFormat.includes(extname.toLocaleLowerCase())) {
          if (tree?.images) {
            tree?.images.push(replacedJsonString(fullPath));
          } else {
            tree.images = [replacedJsonString(fullPath)];
          }
        }
      }
    });

    return tree;
  }
} catch (err) {
  console.error("An error occurred:", err);
}
